{% extends "base.html" %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h2>
        <i class="bi bi-people me-2"></i>用户管理
    </h2>
    <div class="btn-group">
        <button class="btn btn-outline-primary" onclick="refreshUserList()">
            <i class="bi bi-arrow-clockwise me-1"></i>刷新列表
        </button>
        <a href="{{ url_for('admin.dashboard') }}" class="btn btn-outline-secondary">
            <i class="bi bi-arrow-left me-1"></i>返回仪表板
        </a>
    </div>
</div>

<!-- 搜索和筛选 -->
<div class="card mb-4">
    <div class="card-body">
        <form method="GET" class="row g-3">
            <div class="col-md-3">
                <label for="search" class="form-label">搜索用户</label>
                <input type="text" class="form-control" id="search" name="search" 
                       value="{{ search }}" placeholder="用户名、邮箱或姓名">
            </div>
            <div class="col-md-2">
                <label for="role" class="form-label">角色筛选</label>
                <select class="form-select" id="role" name="role">
                    <option value="">全部角色</option>
                    <option value="admin" {% if role_filter == 'admin' %}selected{% endif %}>管理员</option>
                    <option value="student" {% if role_filter == 'student' %}selected{% endif %}>学生</option>
                </select>
            </div>
            <div class="col-md-2">
                <label for="status" class="form-label">状态筛选</label>
                <select class="form-select" id="status" name="status">
                    <option value="">全部状态</option>
                    <option value="active" {% if status_filter == 'active' %}selected{% endif %}>活跃</option>
                    <option value="inactive" {% if status_filter == 'inactive' %}selected{% endif %}>禁用</option>
                </select>
            </div>
            <div class="col-md-3">
                <label for="class" class="form-label">班级筛选</label>
                <select class="form-select" id="class" name="class">
                    <option value="">全部班级</option>
                    {% for class_option in class_options %}
                    <option value="{{ class_option.id }}" {% if class_filter == class_option.id|string %}selected{% endif %}>
                        {{ class_option.name }}
                    </option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">&nbsp;</label>
                <div class="d-grid">
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-search me-1"></i>搜索
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- 用户列表 -->
<div class="card">
    <div class="card-header">
        <h5 class="mb-0">
            <i class="bi bi-list me-2"></i>用户列表
            <span class="badge bg-secondary ms-2">共 {{ users.total }} 个用户</span>
        </h5>
    </div>
    <div class="card-body p-0">
        {% if users.items %}
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light">
                    <tr>
                        <th>ID</th>
                        <th>用户名</th>
                        <th>真实姓名</th>
                        <th>邮箱</th>
                        <th>班级</th>
                        <th>角色</th>
                        <th>状态</th>
                        <th>注册时间</th>
                        <th>最后登录</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for user in users.items %}
                    <tr>
                        <td>{{ user.id }}</td>
                        <td>
                            <div class="d-flex align-items-center">
                                <i class="bi bi-person-circle me-2 text-muted"></i>
                                <strong>{{ user.username }}</strong>
                            </div>
                        </td>
                        <td>{{ user.real_name or '-' }}</td>
                        <td>{{ user.email }}</td>
                        <td>{{ user.class_id if user.class_id is not none else '-' }}</td>
                        <td>
                            {% if user.role == 'admin' %}
                                <span class="badge bg-danger">管理员</span>
                            {% else %}
                                <span class="badge bg-info">学生</span>
                            {% endif %}
                        </td>
                        <td>
                            {% if user.is_active %}
                                <span class="badge bg-success">活跃</span>
                            {% else %}
                                <span class="badge bg-secondary">禁用</span>
                            {% endif %}
                        </td>
                        <td>
                            <small class="text-muted">
                                {{ user.created_at.strftime('%Y-%m-%d %H:%M') if user.created_at else '未知' }}
                            </small>
                        </td>
                        <td>
                            <small class="text-muted">
                                {{ user.last_login.strftime('%Y-%m-%d %H:%M') if user.last_login else '从未登录' }}
                            </small>
                        </td>
                        <td>
                            <div class="btn-group btn-group-sm">
                                <a href="{{ url_for('admin.user_detail', user_id=user.id) }}" 
                                   class="btn btn-outline-info" title="查看详情">
                                    <i class="bi bi-eye"></i>
                                </a>
                                {% if user.id != current_user.id %}
                                <!-- eslint-disable-next-line -->
                                <button class="btn btn-outline-warning" 
                                        onclick="toggleUserStatus({{ user.id }}, {{ user.username|tojson }}, {{ user.is_active|tojson }})"
                                        title="{% if user.is_active %}禁用{% else %}启用{% endif %}用户">
                                    <i class="bi bi-{% if user.is_active %}pause{% else %}play{% endif %}"></i>
                                </button>
                                {% endif %}
                            </div>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        {% else %}
        <div class="text-center py-5">
            <i class="bi bi-people display-1 text-muted"></i>
            <h5 class="mt-3 text-muted">没有找到用户</h5>
            <p class="text-muted">请尝试调整搜索条件</p>
        </div>
        {% endif %}
    </div>
</div>

<!-- 分页 -->
{% if users.pages > 1 %}
<nav aria-label="用户列表分页" class="mt-4">
    <ul class="pagination justify-content-center">
        {% if users.has_prev %}
        <li class="page-item">
            <a class="page-link" href="{{ url_for('admin.users', page=users.prev_num, search=search, role=role_filter, status=status_filter) }}">
                <i class="bi bi-chevron-left"></i> 上一页
            </a>
        </li>
        {% endif %}
        
        {% for page_num in users.iter_pages() %}
            {% if page_num %}
                {% if page_num != users.page %}
                <li class="page-item">
                    <a class="page-link" href="{{ url_for('admin.users', page=page_num, search=search, role=role_filter, status=status_filter) }}">
                        {{ page_num }}
                    </a>
                </li>
                {% else %}
                <li class="page-item active">
                    <span class="page-link">{{ page_num }}</span>
                </li>
                {% endif %}
            {% else %}
            <li class="page-item disabled">
                <span class="page-link">…</span>
            </li>
            {% endif %}
        {% endfor %}
        
        {% if users.has_next %}
        <li class="page-item">
            <a class="page-link" href="{{ url_for('admin.users', page=users.next_num, search=search, role=role_filter, status=status_filter) }}">
                下一页 <i class="bi bi-chevron-right"></i>
            </a>
        </li>
        {% endif %}
    </ul>
</nav>
{% endif %}

<script>
/**
 * 刷新用户列表
 */
function refreshUserList() {
    window.location.reload();
}

/**
 * 切换用户状态
 * @param {number} userId - 用户ID
 * @param {string} username - 用户名
 * @param {boolean} isActive - 当前状态
 */
function toggleUserStatus(userId, username, isActive) {
    const action = isActive ? '禁用' : '启用';
    const confirmMessage = `确定要${action}用户 "${username}" 吗？`;
    
    if (!confirm(confirmMessage)) {
        return;
    }
    
    fetch(`/admin/users/${userId}/toggle_status`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert(data.message, 'success');
            setTimeout(() => {
                window.location.reload();
            }, 1000);
        } else {
            showAlert(data.message, 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('操作失败，请稍后重试', 'error');
    });
}

/**
 * 显示提示消息
 * @param {string} message - 消息内容
 * @param {string} type - 消息类型 (success, error, warning, info)
 */
function showAlert(message, type = 'info') {
    const alertClass = {
        'success': 'alert-success',
        'error': 'alert-danger',
        'warning': 'alert-warning',
        'info': 'alert-info'
    }[type] || 'alert-info';
    
    const alertHtml = `
        <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    
    // 在页面顶部显示提示
    const container = document.querySelector('.container-fluid') || document.body;
    const alertDiv = document.createElement('div');
    alertDiv.innerHTML = alertHtml;
    container.insertBefore(alertDiv.firstElementChild, container.firstChild);
    
    // 3秒后自动消失
    setTimeout(() => {
        const alert = document.querySelector('.alert');
        if (alert) {
            alert.remove();
        }
    }, 3000);
}
</script>
{% endblock %}